package com.bite.springbook.interceptor;

import com.bite.springbook.constant.Constants;
import com.bite.springbook.model.Result;
import com.bite.springbook.model.UserInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Slf4j

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("校验用户是否登入");
        HttpSession session = request.getSession();
        UserInfo userInfo = (UserInfo)session.getAttribute(Constants.USER_SESSION_KEY);
        if(userInfo == null){
            log.warn("用户未登入");
            response.setStatus(401);
            response.setContentType("application/json;charset=utf-8");
            Result result = Result.fail("用户未登录");
            response.getOutputStream().write(objectMapper.writeValueAsString(result).getBytes());
            return false;
        }
        return true;
    }

    /*@Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("执行方法之后");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("渲染视图之后");
    }*/
}
